//
//  ViewController.swift
//  NSURLSessionDemo
//
//  Created by YangZhe on 17/1/18.
//  Copyright © 2017年 kuLetech. All rights reserved.
//
open class YUIViewController: UIViewController,UITextFieldDelegate,URLSessionDelegate{
    public weak var yApplication:YAppDelegate!
    public weak var viewController: UIViewController!
    public var yScreenWidth:CGFloat!
    public var yScreenHeight:CGFloat!
    public var yStatuBarHeight:CGFloat!
    public var yBundle:[String:Any]?
    public var isAlive = true
    private var inited = false
    var notifications = [String]()
    var nsObjectProtocols = [NSObjectProtocol]()
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public init(viewController: UIViewController) {
        self.viewController = viewController
        super.init(nibName: nil, bundle: nil)
        self.initTheme()
    }

    override final public func viewDidLoad() {
        super.viewDidLoad()
        if self.viewController == nil { self.viewController = self }
        self.automaticallyAdjustsScrollViewInsets = false
    }
    
    override final public func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(!yIsShowNavigationBar(), animated: true)
        yViewWillAppear()
    }
    
    override final public func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        yViewDidAppear()
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        yViewWillDisappear()
    }
    
    override final public func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !inited {
            inited = true
            yScreenWidth = self.view.frame.width
            yScreenHeight = self.view.frame.height
            yStatuBarHeight = getStatuBarHeight()
            initTheme()
            initTextFieldDelegate(view: self.view)
            yApplication = (UIApplication.shared.delegate as? YAppDelegate)
            yPreReadyWebView()
            yOnCreate()
        }
    }
    
    public func initTheme(){
        self.view.tintColor = YConfig.themeColor
        
        self.extendedLayoutIncludesOpaqueBars = false
        
        if let navigationBarBackgroundImage = YConfig.navigationBarBackgroundImage{
            viewController.navigationController?.navigationBar.barTintColor = UIColor.clear
            viewController.navigationController?.navigationBar.setBackgroundImage(UIImage(named: navigationBarBackgroundImage)?.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), resizingMode: .stretch), for: .default)
            if #available(iOS 13.0, *) {
                let appearance = UINavigationBarAppearance()
                appearance.configureWithOpaqueBackground()
                appearance.backgroundImage = UIImage(named: navigationBarBackgroundImage)
                appearance.backgroundImageContentMode = .scaleToFill
                appearance.titleTextAttributes[.foregroundColor] = YConfig.navigationTintColor
                appearance.shadowColor = .clear
//                appearance.shadowImage = UIImage()
                viewController.navigationController?.navigationBar.standardAppearance = appearance
                viewController.navigationController?.navigationBar.scrollEdgeAppearance = viewController.navigationController?.navigationBar.standardAppearance
            }
        } else {
            viewController.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
            viewController.navigationController?.navigationBar.barTintColor = YConfig.navigationBarTintColor
        }
        viewController.navigationController?.navigationBar.isTranslucent = false
        viewController.navigationController?.navigationBar.barStyle = .default
        viewController.navigationController?.navigationBar.tintColor = YConfig.navigationTintColor
        viewController.navigationController?.navigationBar.titleTextAttributes =  [NSAttributedString.Key.foregroundColor: YConfig.navigationTintColor]
        
        self.tabBarController?.tabBar.isTranslucent = false
        self.tabBarController?.tabBar.barTintColor = YConfig.tabBarTintColor
        self.tabBarController?.tabBar.tintColor = YConfig.tabTintColor
    }
    
    private func getStatuBarHeight() -> CGFloat {
//        if #available(iOS 11.0, *) {
//            return self.view.safeAreaInsets.top
//        } else {
//            return 20
//        }
        return UIApplication.shared.statusBarFrame.height
    }
    
    open func unRegisterBroadcasts() {
        nsObjectProtocols.forEach {
            NotificationCenter.default.removeObserver($0)
        }
        nsObjectProtocols.removeAll()
        NotificationCenter.default.removeObserver(self)
    }
    
    private func initTextFieldDelegate(view:UIView){
        if yIsUITextFieldDelegate() {
            for subView in view.subviews {
                if subView is UITextField {
                    (subView as! UITextField).delegate = self
                }
                initTextFieldDelegate(view: subView)
            }
        }
    }
    
    private func clearTableView(view:UIView){
        for subView in view.subviews {
            if subView is UITableView {
                let tableView = subView as! UITableView
                tableView.mj_header = nil
            }
            clearTableView(view: subView)
        }
    }
    
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder() 
        return true
    }
    
    open override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        self.onDestory()
        super.dismiss(animated: flag,completion:completion)
    }
    
    override open func didMove(toParent parent: UIViewController?) {
        if parent == nil {
            onDestory()
        }
    }
    
    func onDestory(){
        if isAlive {
            isAlive = false
            viewController = nil
            unRegisterBroadcasts()
            yCloseKeyBoard()
            yDismissLoadingProgress()
            self.clearTableView(view: self.view)
            self.yOnDestory()
        }
    }
    
    open func yOnCreate(){}
    open func yViewWillAppear() {}
    open func yViewWillDisappear() {}
    open func yViewDidAppear() {}
    open func yOnDestory(){}

    open func yPreReadyWebView(){
//        let readyWebView = UIWebView(frame: .zero)
//        self.view.addSubview(readyWebView)
//        readyWebView.loadHTMLString("", baseURL: nil)
//        if YConfig.preYWebView && YConfig.yWebView == nil {
//            YConfig.yWebView = YWebView(frame: .zero)
//            YConfig.yWebView?.loadHTMLString("", baseURL: nil)
//            self.view.addSubview(YConfig.yWebView!)
//        }
//        _ = yRunOnUIThreadDelay(delay: 5) {
//            readyWebView.removeFromSuperview()
//            YConfig.yWebView?.removeFromSuperview()
//        }
    }
    
    open func yInflateView(name:String, index:Int = 0) -> UIView?{
        return Bundle.main.loadNibNamed(name, owner: self, options: nil)?[index] as? UIView
    }

    open func yCloseKeyBoard(){
        if self.view != nil {
            yRunOnUIThread {
                self.view.endEditing(true)
            }
        }
    }
    
    open func yIsUITextFieldDelegate() -> Bool{
        return true
    }
    
    open func yIsShowNavigationBar() -> Bool{
        return true
    }
}
